/**  
 * All rights Reserved, Designed By www.beonelot.com
 * @Package: com.jinxin.platform.eleinspect.controller
 * @Filename: EleinspectMappingPointItemsController.java
 * @Description: TODO(EleinspectMappingPointItemsController)
 * @author: 金鑫智慧
 * @date: 2020-03-30
 * @version: V1.0
 * @Copyright: 2020 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdelecinspect.controller;


import com.jinxin.platform.cdelecinspect.domain.SysUserVO;
import com.jinxin.platform.cdelecinspect.mapper.*;
import com.jinxin.platform.cdelecinspect.mapper.pojo.*;
import com.jinxin.platform.cdelecinspect.result.ResultEntity;
import com.jinxin.platform.cdelecinspect.result.ResultTool;
import com.jinxin.platform.cdelecinspect.rpc.SysUserRpc;
import com.jinxin.platform.cdelecinspect.service.EleinspectItemsRecordService;
import com.jinxin.platform.cdelecinspect.service.EleinspectItemsService;
import com.jinxin.platform.cdelecinspect.service.EleinspectMappingPointItemsService;
import com.jinxin.platform.cdelecinspect.utils.DateUtils;
import com.jinxin.platform.cdelecinspect.utils.UploadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TODO(EleinspectMappingPointItemsController)
 * @Classn: EleinspectMappingPointItemsController
 * @author Lynn
 * @date 2020-03-30
 */
@Slf4j
@RestController
@RequestMapping("/insPointRecord")
public class EleinspectMappingPointItemsController {
    @Autowired
    private EleinspectMappingPointItemsService eleinspectMappingPointItemsService;
    @Autowired
    private EleinspectLineManageMapper lineManageMapper;
    @Autowired
    private EleinspectRecordMapper recordMapper;
    @Autowired
    private EleinspectMappingPointItemsMapper pointItemsMapper;
    @Autowired
    private EleinspectAttachmentMapper attachmentMapper;
    @Autowired
    private EleinspectItemsRecordService eleinspectItemsRecordService;
    @Autowired
    private EleinspectItemsService eleinspectItemsService;
    @Autowired
    private EleinspectTaskMapper taskMapper;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private CdelecinspectStatisticsMapper statisticsMapper;
    @Value("${platform.upload}")
    private String uploadPath;


    @RequestMapping("/listByCondition")
    public Map<String,Object> listByCondition(String point, String line, String startTime, @RequestParam(required = false)String recordInspectId,
                                              String endTime, @RequestParam long page, @RequestParam long limit,Integer status){
        Map<String,Object> resultMap = new HashMap<>();
        HashMap<String,Object> param = new HashMap<>();
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        param.put("point_name", point);
        param.put("line_id", line);
        param.put("recordInspectId", recordInspectId);
        param.put("page", page);
        param.put("limit", limit);
        param.put("status", status);
        resultMap.put("code",0);
        resultMap.put("msg","");
        List<EleinspectPointRecords> list =
                eleinspectMappingPointItemsService.listPointRecords(param);
        resultMap.put("count",eleinspectMappingPointItemsService.listPointRecordsCount(param));
        resultMap.put("data",list);
        return resultMap;
    }

    @RequestMapping("/listPointItems")
    public Map<String,Object> listPointItems(String recordId, @RequestParam long page, @RequestParam long limit){
        Map<String,Object> resultMap = new HashMap<>();
        HashMap<String,Object> param = new HashMap<>();
        param.put("itemPointRecordId", recordId);
        List<EleinspectItemRecordVo> itemRecordVoList = new ArrayList<>();
        List<EleinspectItemRecord> list = eleinspectItemsRecordService.list(param);
        for (EleinspectItemRecord eleinspectItemRecord : list){
            EleinspectItemRecordVo eleinspectItemRecordVo = new EleinspectItemRecordVo();
            EleinspectItems eleinspectItems = eleinspectItemsService.selectByKey(eleinspectItemRecord.getItemRecordItemId());
            eleinspectItemRecordVo.setItemsId(eleinspectItems.getItemsId());
            eleinspectItemRecordVo.setItemsName(eleinspectItems.getItemsName());
            eleinspectItemRecordVo.setItemRecordStatus(eleinspectItemRecord.getItemRecordStatus());
            eleinspectItemRecordVo.setItemRecordDescription(eleinspectItemRecord.getItemRecordDescription());
            eleinspectItemRecordVo.setItemRecordId(eleinspectItemRecord.getItemRecordId());
            itemRecordVoList.add(eleinspectItemRecordVo);
        }
        resultMap.put("data",itemRecordVoList);
        resultMap.put("code",0);
        resultMap.put("msg","");
        return resultMap;
    }

    @GetMapping("getLineList")
    public ResultEntity getLineList(){
        List<EleinspectLineManage> list = lineManageMapper.list(new HashMap());
        if(list.size() > 0){
            return ResultTool.ok(list, "success");
        }else {
            return ResultTool.fail( "fail");
        }
    }

    @GetMapping("/deleteAll")
    public ResultEntity deleteAll(String params) {
        if(eleinspectMappingPointItemsService.deleteAll(params)){
            return ResultTool.ok("Success");
        }
        return ResultTool.fail("Fail");
    }
    @GetMapping("/deleteRecord")
    @Transactional
    public ResultEntity deleteRecord(String rid, String pid, String mid) {
        if (!StringUtils.isEmpty(rid)) {
            int num = recordMapper.deleteByKey(rid);
            if (num > 0){
                eleinspectMappingPointItemsService.deletePlItemsByIds(Arrays.asList(pid));
                pointItemsMapper.deleteByKey(mid);
                return ResultTool.ok("Success");
            }else {
                return ResultTool.fail("Fail");
            }
        }
        return ResultTool.fail("参数错误");
    }
    @GetMapping("/getScanPics/{itemsId}")
    public ResultEntity getScanPics(@PathVariable("itemsId") String itemsId) {
        if(!StringUtils.isEmpty(itemsId)){
            HashMap param = new HashMap();
            param.put("itemsId", itemsId);
            HashMap params2 = new HashMap();
            params2.put("mainId", itemsId);
            List<EleinspectAttachment> attachmentList = attachmentMapper.list(params2);
            return ResultTool.ok(attachmentList);
        }
        return ResultTool.ok("no record");
    }

    @GetMapping("/getClockInDetail")
    public ResultEntity getClockInDetail(String taskId,String pointId, String lineId) {
        if(!StringUtils.isEmpty(taskId) && !StringUtils.isEmpty(pointId) && !StringUtils.isEmpty(lineId)){
            HashMap param = new HashMap();
            param.put("recordLineId", lineId);
            param.put("recordPointId", pointId);
            param.put("recordTaskId", taskId);
            EleinspectRecord eleinspectRecord = recordMapper.selectOne(param);
            if(eleinspectRecord != null){
                HashMap params2 = new HashMap();
                params2.put("mainId", eleinspectRecord.getRecordId());
                List<EleinspectAttachment> attachmentList = attachmentMapper.list(params2);
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("imgs",attachmentList);
                resultMap.put("clockinTime",eleinspectRecord.getRecordClockinTime());
                return ResultTool.ok(resultMap);
            }
        }
        return ResultTool.ok("no record");
    }

    @PostMapping("/submitItem")
    public ResultEntity submitItem(EleinspectMappingPointItems mappingPointItems,String lineId){
        return eleinspectMappingPointItemsService.submitItem(mappingPointItems,lineId);
    }
    // 点位记录提交
    @PostMapping("/submitPoint")
    public ResultEntity submitPoint(String pointId, String taskId,String lineId){
        return eleinspectMappingPointItemsService.submitPoint(pointId, taskId,lineId);
    }
    // 打卡
    @PostMapping("/clockIn")
    public ResultEntity clockIn(EleinspectRecord record){
        return eleinspectMappingPointItemsService.clockIn(record);
    }

    // 完成巡检
    @PostMapping("/completeInspect")
    public ResultEntity completeInspect(String taskId){
        if(StringUtils.isEmpty(taskId)){
            log.info("completeInspect 参数错误");
            return ResultTool.fail("参数错误");
        }
        HashMap param = new HashMap();
        param.put("recordTaskId",taskId);
        List<EleinspectRecord> recordList = recordMapper.list(param);
        boolean allFinished = true;
        for (EleinspectRecord record : recordList) {
            if(StringUtils.isEmpty(record.getRecordPointStatus())){
                allFinished = false;
                break;
            }
        }
        if(!allFinished){
            return ResultTool.fail("请完成所有巡检项后提交");
        }
        EleinspectTask eleinspectTask = taskMapper.selectByKey(taskId);
        Date now = new Date();
        EleinspectTask item = new EleinspectTask();
        // 任务状态: 0未开始1进行中2提早完成3按时完成4超时完成5已取消6已过期
        if(now.after(eleinspectTask.getEarliestFinishTime()) && now.before(eleinspectTask.getLatestFinishTime())){
            item.setStatus(3);
        }else if (now.before(eleinspectTask.getEarliestFinishTime())){
            item.setStatus(2);
        }else if(now.after(eleinspectTask.getLatestFinishTime())){
            item.setStatus(4);
        }
        item.setId(taskId);
        item.setIsSubmit(1); // 已提交
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        item.setFinishTime(df.format(new Date()));
        int count = taskMapper.updateByKey(item);
        if(count > 0){
            SysUserVO currentUser = sysUserRpc.getCurrentUser();
            if(currentUser != null){
                String userId = currentUser.getUserId();
                CdelecinspectStatistics statistics = statisticsMapper.getById(userId);
                if(statistics != null){
                    Date latestInspectTime = statistics.getLatestInspectTime();
                    if(latestInspectTime != null){
                        long min = DateUtils.dateDiff(latestInspectTime, new Date());
                        if(min > 0){
                            statistics.setInspectCount(statistics.getInspectCount()+1);
                            statistics.setLatestInspectTime(new Date());
                            statistics.setTotalInspectDur(statistics.getTotalInspectDur()+min);
                            statisticsMapper.update(statistics);
                            log.info("更新统计表数据成功");
                        }
                    }

                }
            }
            return ResultTool.ok("提交成功");
        }
        return ResultTool.fail("提交失败，请重试");
    }

    @PostMapping("/uploadFiles")
    public Map<String,Object> uploadFiles(MultipartFile file) {
        String filePath = UploadFileUtil.uploadFile(file, this.uploadPath, "");
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",0);
        resultMap.put("msg","success");
        resultMap.put("filePath",filePath);
        resultMap.put("fileName",file.getOriginalFilename());
        return resultMap;
    }
}
